package com.fanshuai.controller;

import io.micrometer.core.instrument.*;
import io.micrometer.prometheus.PrometheusMeterRegistry;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.util.Random;

@RestController
public class CustomController {
    /**
     * spring boot actuator 自动注册一个CompositeMeterRegistry，并添加一个registry到CompositeMeterRegistry中
     * 项目依赖micrometer-registry-prometheus时，添加prometheusMeterRegistry
     *
     * spring boot actuator默认注册JVM相关信息到prometheusMeterRegistry中
     */
    @Resource
    private PrometheusMeterRegistry prometheusMeterRegistry;

    private Timer timer;
    private Gauge gauge;
    private Counter counter;
    private DistributionSummary summary;

    private Integer value;

    private Random random = new Random(System.currentTimeMillis());

    @PostConstruct
    public void init() {
        timer = Timer.builder("timer")
                .tags()
                .publishPercentiles(0.5, 0.75, 0.9, 0.95, 0.98, 0.99)
                .publishPercentileHistogram(false)
                .register(prometheusMeterRegistry);

        summary = DistributionSummary.builder("summary")
                .publishPercentiles(0.5, 0.75, 0.9, 0.95, 0.98, 0.99)
                .register(prometheusMeterRegistry);

        prometheusMeterRegistry.gauge("gauge", value, Integer::intValue);
        gauge = prometheusMeterRegistry.get("gauge").gauge();

        counter = prometheusMeterRegistry.counter("counter");
    }

    @Scheduled(fixedRate = 1000)
    public void schedule() {
        System.out.println("schedule");

        counter.increment();

        timer.record(Duration.ofMillis(random.nextInt(1000)));
        summary.record(random.nextInt(1000));

        value = random.nextInt(10);
    }

    @RequestMapping("/prometheus")
    public void prometheus(HttpServletResponse response) throws Exception {
        String output = prometheusMeterRegistry.scrape();

        response.getWriter().print(output);
        response.getWriter().flush();
    }
}
